const Router = require('koa-router')
const jwt = require('koa-jwt')
const User = require('../models/User')
const config = require('../utils/config')

const router = new Router({
  prefix: '/public',
})

router.get('/', function* () {
  yield this.render('index')
})

router.post('/register', function* () {
  const { body } = this.request
  const user = new User(body)
  const rs = yield user.save()
  this.body = {
    error: false,
    data: rs,
  }
})

router.post('/login', function* () {
  this.checkBody('phone').len(11, 11, '手机号有误')
  this.checkBody('password').len(6, 24, '密码格式不正确, 6 - 24位')
  if (this.errors) {
    this.throw(400, {message: this.errors})
    return
  }
  const { body } = this.request
  const user = yield User.findOne({phone: body.phone})
  if (!user) {
    this.throw(404, 'User does not exist.')
    return
  }
  const jwtUser = {
    id: user._id.toString(),
    phone: user.phone,
    role: user.role,
  }
  user._doc.token = jwt.sign(jwtUser, config.jwt.secret, config.jwt.expiresInMinutes)
  this.body = user
})

module.exports = router